<template>
  <div class="app-container">
    <el-scrollbar :wrap-class="{wrapClass: true}" class="form-scrollbar">
      <el-form ref="form" class="form-company" :rules="rules" :model="userInfo" label-width="110px">
        <el-card v-loading="infoLoading" shadow="never">
          <div slot="header" class="clearfix">
            <span>我的资料</span>
            <el-button
              style="margin-left: 20px;padding: 0;" type="text" @click="editPassword">修改密码
            </el-button>
          </div>
          <div class="basic-data">
            <!--            <div class="tip-text">-->
            <!--              基本信息-->
            <!--            </div>-->
            <div class="basic_info">
              <el-form-item label="用户名">
                <el-input v-model="userInfo.username" style="max-width: 400px" disabled/>
              </el-form-item>
              <el-form-item label="姓名" prop="name" class="truename">
                <el-input
                  v-model="userInfo.name"
                  style="max-width: 400px"
                  @input="checkTrim('name')"
                  autocomplete="off"
                >
                  <el-button slot="append" @click="updateName">更新</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="创建时间">
                <span>{{ userInfo.created }}</span>
              </el-form-item>
              <el-form-item label="到期时间:">
                <span>{{ userInfo.validity }}</span>
              </el-form-item>
            </div>

            <div class="basic_avatar">
              <div style="float: left;width: 300px">
                <el-form-item>
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadAction"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    accept=".jpeg,.png,.jpg"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"/>
                  </el-upload>
                  <el-alert
                    style="height: 30px;width:178px"
                    title="图片不可大于1M"
                    type="warning"
                    :closable="false"
                    show-icon
                  />
                </el-form-item>
              </div>
            </div>
          </div>
          <el-divider/>
        </el-card>
      </el-form>

      <el-dialog
        class="update-password"
        title="更新密码"
        :visible.sync="passwordState"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
      >
        <el-form ref="formPassword" label-width="80px" :rules="rulePassword"
                 v-loading="passwordLoading" :model="passwordInfo">
          <el-form-item label="原密码" prop="originalPassword">
            <el-input v-model="passwordInfo.originalPassword"/>
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model="passwordInfo.password"/>
          </el-form-item>
          <el-form-item label="再次输入" prop="checkPassword">
            <el-input v-model="passwordInfo.checkPassword"/>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="passwordLoading" @click="updatePassword">提 交</el-button>
        <el-button @click="passwordState = false">取 消</el-button>
        </span>
      </el-dialog>

    </el-scrollbar>
  </div>
</template>

<script>
import { UserModule } from '@/store/modules/user'
import common from '@/utils/common'
import { postAction } from '@/api/common'

export default {
  name: 'userCenter',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度 6 到 16 个字符'))
      } else if (value.length > 16) {
        callback(new Error('密码长度 6 到 16 个字符'))
      } else if (value == this.passwordInfo.originalPassword) {
        callback(new Error('不能跟原密码一样!'))
      }
      this.$refs.formPassword.validateField('confirmPassword')
      callback()
    }
    const validatePass2 = (rule, value, callback) => {
      console.log(value, this.passwordInfo)
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value == this.passwordInfo.originalPassword) {
        callback(new Error('不能跟原密码一样!'))
      } else if (value !== this.passwordInfo.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      uploadAction: '/api/UserCompany/UploadAvatarImg',
      userInfo: {
        username: '',
        name: '',
        avatar: '',
        created: '',
        validity: ''
      },
      infoLoading: false,
      passwordInfo: {
        originalPassword: '',
        password: '',
        checkPassword: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'change'
          }
        ]
      },
      passwordLoading: false,
      passwordState: false,
      rulePassword: {
        originalPassword: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.infoLoading = true
      const { data } = await postAction({}, 'UserCompany/GetUserCenterInfo')
      // console.log(data)
      this.userInfo = data
      this.infoLoading = false
    },
    checkTrim(obj) {
      this.userInfo[obj] = common.checkAllTrim(this.userInfo[obj])
    },
    handleAvatarSuccess(res, file) {
      // eslint-disable-next-line eqeqeq
      if (res.code == 20000) {
        this.userInfo.avatar = res.data
        UserModule.SET_AVATAR(res.data)
        this.infoLoading = false
      } else {
        this.$message.error(res.message)
        this.infoLoading = false
      }
    },
    beforeAvatarUpload(file) {
      this.infoLoading = true
      const isType = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG,JPEG,PNG 格式!')
        this.infoLoading = false
      }
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        this.infoLoading = false
      }
      return isType && isLt1M
    },
    updateName() {
      this.$confirm('是否确认更新姓名为：' + this.userInfo.name, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await postAction({ name: this.userInfo.name }, 'UserCompany/SubUserCenterInfo')
        UserModule.setName(this.userInfo.name)
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    editPassword() {
      this.passwordInfo = {
        originalPassword: '',
        password: '',
        checkPassword: ''
      }
      this.passwordState = true
    },
    updatePassword() {
      this.$refs.formPassword.validate(async(valid) => {
        // form验证
        if (valid) {
          this.passwordLoading = true
          await postAction(this.passwordInfo, 'UserCompany/SubUserCenterPassword')
          this.passwordLoading = false
          this.passwordState = false
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

.form-scrollbar {
  height: calc(100vh - 75px);
}

.form-company {
  min-width: 700px;
}

.app-container {
  height: calc(100vh - 65px);
}

.el-card__footer {
  bottom: 0;
  padding: 18px 20px;
  border-top: 1px solid #EBEEF5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

/deep/ .el-card__body {
  padding: 0;
}

.truename /deep/ .el-button {
  background-color: #409EFF;
  color: #fff;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.truename /deep/ .el-button:hover {
  background-color: #66B1FF;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fbfdff;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.basic_info {
  float: left;
  /*min-height: 260px;*/
  width: 50%;
  min-width: 350px;
}

.basic_avatar {
  float: left;
  /*height: 300px;*/
  width: 50%;
  min-width: 510px;
}

.avatar-info {
  float: left;
  margin-top: 20px;
}

/deep/ .el-form-item {
  margin-bottom: 15px;
}

.avatar-info /deep/ .el-form-item {
  margin-bottom: 0;
  text-align: justify;
  text-align-last: justify;
}

.basic-data {
  padding: 20px 20px 10px 20px;
}

.basic-data:after {
  content: "020";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

/deep/ .el-divider {
  margin: 0;
}

.tip-text {
  margin: 0 0 15px 10px;
  font-size: 15px;
}
.update-password /deep/ .el-dialog {
  margin-top: 30vh !important;
  min-width: 400px;
  width: 500px;
}

.update-password /deep/ .el-dialog__body {
  padding: 20px 20px 0 20px;
}
</style>
